
package com.gs.netty.client;

import com.gs.netty.client.exception.RemotingException;
import com.gs.netty.client.exception.WebSocketRemotingSendRequestException;
import com.gs.netty.client.exception.WebSocketRemotingTimeoutException;


import com.gs.netty.core.SemaphoreReleaseOnlyOnce;
import com.gs.netty.websocket.remoting.WebSocketInvocation;

import io.netty.channel.Channel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;


public class ResponseFuture {
    /**
     *
     */
    private final Channel channel;
    /**
     * 请求Id
     */
    private final Integer requestId;
    /**
     * 请求
     */
    private final WebSocketInvocation request;
    /**
     * 请求超时时间
     */
    private final long timeoutMillis;
    /**
     * 回调函数
     */
    private final InvokeCallback invokeCallback;

    /**
     * 调用开始时间
     */
    private final long beginTimestamp = System.currentTimeMillis();
    private final SemaphoreReleaseOnlyOnce once;

    private final CountDownLatch countDownLatch = new CountDownLatch(1);

    private final AtomicBoolean executeCallbackOnlyOnce = new AtomicBoolean(false);
    /**
     * 响应结果
     */
    private volatile WebSocketInvocation responseCommand;

    private volatile boolean sendRequestOK = false;
    private volatile Throwable cause;
    private volatile boolean interrupted = false;



    public ResponseFuture(Channel channel, Integer requestId, WebSocketInvocation request, long timeoutMillis, InvokeCallback invokeCallback
                          ,SemaphoreReleaseOnlyOnce once) {
        this.channel = channel;
        this.requestId = requestId;
        this.request = request;
        this.timeoutMillis = timeoutMillis;
        this.invokeCallback = invokeCallback;
        this.once =once;
    }

    // 执行回答函数
    public void executeInvokeCallback() {
        if (invokeCallback != null) {
            if (this.executeCallbackOnlyOnce.compareAndSet(false, true)) {
                WebSocketInvocation response = getResponseCommand();
                if (response != null) {
                    // 回调
                    invokeCallback.succeed(response);
                } else {

                    if (!isSendRequestOK()) {// 判断是否发送成功
                        invokeCallback.fail(new WebSocketRemotingSendRequestException(channel.remoteAddress().toString(), getCause()));
                    } else if (isTimeout()) { // 判断是否超时
                        invokeCallback.fail(new WebSocketRemotingTimeoutException(channel.remoteAddress().toString(), getTimeoutMillis(), getCause()));
                    } else {
                        invokeCallback.fail(new RemotingException(getRequestCommand().toString(), getCause()));
                    }
                }
                invokeCallback.complete(this);
            }
        }
    }

    public void interrupt() {
        interrupted = true;
        executeInvokeCallback();
    }

    public void release() {
        if (this.once != null) {
            this.once.release();
        }
    }

    public boolean isTimeout() {
        long diff = System.currentTimeMillis() - this.beginTimestamp;
        return diff > this.timeoutMillis;
    }

    public WebSocketInvocation waitResponse(final long timeoutMillis) throws InterruptedException {
        this.countDownLatch.await(timeoutMillis, TimeUnit.MILLISECONDS);
        return this.responseCommand;
    }

    public void putResponse(final WebSocketInvocation responseCommand) {
        this.responseCommand = responseCommand;
        this.countDownLatch.countDown();
    }

    public long getBeginTimestamp() {
        return beginTimestamp;
    }

    public boolean isSendRequestOK() {
        return sendRequestOK;
    }

    public void setSendRequestOK(boolean sendRequestOK) {
        this.sendRequestOK = sendRequestOK;
    }

    public long getTimeoutMillis() {
        return timeoutMillis;
    }

    public InvokeCallback getInvokeCallback() {
        return invokeCallback;
    }

    public Throwable getCause() {
        return cause;
    }

    public void setCause(Throwable cause) {
        this.cause = cause;
    }

    public WebSocketInvocation getResponseCommand() {
        return responseCommand;
    }

    public void setResponseCommand(WebSocketInvocation responseCommand) {
        this.responseCommand = responseCommand;
    }

    public Integer getRequestId() {
        return requestId;
    }

    public WebSocketInvocation getRequestCommand() {
        return request;
    }

    public Channel getChannel() {
        return channel;
    }

    public boolean isInterrupted() {
        return interrupted;
    }

    @Override
    public String toString() {
        return "ResponseFuture [responseCommand=" + responseCommand + ", sendRequestOK=" + sendRequestOK
            + ", cause=" + cause + ", requestId=" + requestId + ", timeoutMillis=" + timeoutMillis
            + ", invokeCallback=" + invokeCallback + ", beginTimestamp=" + beginTimestamp
            + ", countDownLatch=" + countDownLatch + "]";
    }
}
